/**
 * sms.send(手机号) 发送短信验证码
 * sms.verify(手机号,验证码) 校验验证码是否正确
 **/

const repairStatement = require("../common/sql_sentences/repair")
const repairerStatement = require("../common/sql_sentences/repairer")

const Core = require("@alicloud/pop-core")
const _ = require("lodash")

const client = new Core({
  accessKeyId: 'bGRhazkxZTgzZGYwZDFjMGUxZmZhMmFh',
  accessKeySecret: 'bGRhazkxZTgzZGYwZDFjMGUxZmZhMmFh',
  endpoint: 'https://apisms.landui.com',
  apiVersion: '2017-05-25'
})

const params = {
  "SignName": "校园报修平台",
  "TemplateCode": "1690",
}

const requestOption = {
  method: 'POST',
  formatParams: false,
}

exports.send = function (id) {
  return new Promise(async (resolve, reject) => {
    // 查询报修单
    let sqlStr = repairStatement.idSelect(id)
    let repair = await RunSQL(sqlStr)

    // 查询维修人员 -> 获取联系电话
    sqlStr = repairerStatement.select(repair[0].r_number)
    repairer = await RunSQL(sqlStr)

    console.log(repairer[0].phone, repair[0].place, repair[0].type_name)
    resolve()
    try {
      client
        .request(
          "SendSms",
          {
            ...params,
            'PhoneNumbers': repairer[0].phone,
            'TemplateParam': `{\"address\":\"${repair[0].place}\", \"type\":\"${repair[0].type_name}\"}`
          },
          requestOption
        )
        .then(
          (result) => {
            if (
              result.Message &&
              result.Message == "OK" &&
              result.Code &&
              result.Code == "OK"
            ) {
              resolve()
            } else {
              reject('短信发送失败！')
            }
          },
          (ex) => {
            reject(ex)
          }
        )
    } catch (error) {
      reject(error)
    }
  })
}